/*
 * Copyright 2023 OceanBase
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { useContext, useEffect, useMemo, useState } from 'react';
import { IDatabase, DBType, DatabaseGroup } from '@/d.ts/database';
import { DataBaseTreeData } from '../Nodes/database';
import { TreeDataNode } from '../type';
import ResourceTree from '..';
import login from '@/store/login';
import ResourceTreeContext from '@/page/Workspace/context/ResourceTreeContext';
import datasourceStatus from '@/store/datasourceStatus';
import useGroupData from './useGroupData';
import { getDataSourceModeConfig } from '@/common/datasource';
import { isPhysicalDatabase } from '@/util/database';
import { getGroupKey, getSecondGroupKey } from '../const';

const DatabaseTree = function () {
  const {
    databaseList,
    reloadDatabaseList,
    pollingDatabase,
    groupMode,
    reloadDatasourceList,
    datasourceList,
  } = useContext(ResourceTreeContext);
  const { DatabaseGroupMap } = useGroupData({
    databaseList,
    // 个人空间展示全量的数据源,不会根据配置来
    datasourceList: login.isPrivateSpace() ? datasourceList : [],
    filter: (db: IDatabase) => {
      const config = getDataSourceModeConfig(db?.dataSource?.type);
      if (!config?.features?.groupResourceTree && isPhysicalDatabase(db)) {
        return false;
      }
      return db.existed;
    },
  });
  const [defaultExpandedKeys, setDefaultExpandedKeys] = useState<React.Key[]>([]);
  async function reload() {
    await reloadDatabaseList();
    await reloadDatasourceList();
  }

  useEffect(() => {
    if (databaseList?.length) {
      const ids: Set<number> = new Set();
      databaseList.forEach((d) => {
        if (d.type !== DBType.LOGICAL && !!d.dataSource?.id) {
          ids.add(d.dataSource?.id);
        }
      });
      datasourceStatus.asyncUpdateStatus(Array.from(ids));
    } else {
    }
  }, [databaseList]);

  /**
   * 全部数据库节点数据，做缓存处理
   */
  const allDatabaseDataNodeMap = useMemo(() => {
    const DatabaseNodeMap = new Map<number, TreeDataNode>();
    const databases = DatabaseGroupMap[DatabaseGroup.none];
    databases?.forEach((db) => {
      DatabaseNodeMap.set(db.id, DataBaseTreeData(undefined, db, db.id, true));
    });
    return DatabaseNodeMap;
  }, [databaseList]);

  useEffect(() => {
    initDefaultExpandedKeys();
  }, [databaseList]);

  const initDefaultExpandedKeys = () => {
    const defaultExpandedKeys = [];
    [
      DatabaseGroup.project,
      DatabaseGroup.dataSource,
      DatabaseGroup.tenant,
      DatabaseGroup.cluster,
      DatabaseGroup.environment,
      DatabaseGroup.connectType,
    ].forEach((item) => {
      const group = DatabaseGroupMap?.[item]?.entries()?.next()?.value?.[1];
      defaultExpandedKeys.push(getGroupKey(group?.mapId, item));
      if (
        [
          DatabaseGroup.cluster,
          DatabaseGroup.environment,
          DatabaseGroup.connectType,
          DatabaseGroup.tenant,
        ].includes(item)
      ) {
        const secondGroup = group?.secondGroup?.entries()?.next()?.value?.[1];
        defaultExpandedKeys.push(getSecondGroupKey(group?.mapId, secondGroup?.mapId, item));
      }
    });
    setDefaultExpandedKeys(defaultExpandedKeys);
  };

  return (
    <ResourceTree
      stateId={'resourceTree'}
      reload={() => reload()}
      databases={[...(DatabaseGroupMap[groupMode]?.values() || [])]}
      allDatabasesMap={DatabaseGroupMap[DatabaseGroup.none]}
      pollingDatabase={pollingDatabase}
      defaultExpandedKeys={defaultExpandedKeys}
      DatabaseDataNodeMap={allDatabaseDataNodeMap}
    />
  );
};

export default DatabaseTree;
